from common.base import Base,open_browser
from page.login_page import LoginPage, login_url
import time

class Commodity(Base):
    """制作导航栏的定位器"""
    phone_loc=("css selector","#category_tree > div:nth-child(1) > div.cat1 > a")
    work_loc=("link text","办公")
    electricapp_loc=("link text","家用电器")
    computer_loc=("link text","电脑")
    clothes_loc=("link text","男装/女装")
    codefashin_loc=("css selector","#category_tree > div:nth-child(6) > div > a")
    playtoy_loc=("link text","母婴/玩具")
    foods_loc=("link text","食品/酒类")
    sports_loc=("link text","运动/户外")
    #把定位器制作成一个列表
    cho=[
        phone_loc,
        work_loc,
        electricapp_loc,
        computer_loc,
        clothes_loc,
        codefashin_loc,
        playtoy_loc,
        foods_loc,
        sports_loc
    ]


    #制做商品标题定位器
    goods_loc = ("css selector", "div.goods-title>a")
    def get_goods_titles(self):
        """定位获取所有商品标题"""
        goods_elements = self.find_elements(self.goods_loc)
        #定义一个空列表来白村所有标题
        titles = []
        #遍历说所有定位器
        for i in goods_elements:
            #得到每个标题的文本
            title = i.get_attribute("title")
            #添加到列表中
            titles.append(title)
        # 返回存好标题的列表
        return titles
    def click_all_goods(self):
        """点击全部商品--浏览商品"""
        titles = self.get_goods_titles()
        for i in titles:
            # 通过title 文本定位每个商品
            good_loc = ("css selector", f"a[title='{i}']")
            # 点击定位好的商品
            self.click(good_loc)
            time.sleep(2)
            # 浏览器后退
            self.back()
    def chioce_goods(self, goods_name):
        titles = self.get_goods_titles()
        if goods_name in titles:
            good_loc = ("css selector", f"a[title='{goods_name}']")
            self.click(good_loc)
        else:
            print("所选商品不存在")









if __name__ == '__main__':
    driver = open_browser()
    goods = Commodity(driver)
    goods.open_url(login_url)
    # login.choose()
    # time.sleep(3)
    # login.close_browser()
    def choose():
        for i in goods.cho:
            goods.click(i)
            # self.click_goods_all()
            goods.click_goods_all()
            time.sleep(2)
            goods.back()
    choose()
    driver.quit()